package le.cn.aio.server;

import cn.le.util.info.HostInfo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

public class AsyncTimeServerHandler implements Runnable {
    // CountDownLatch是一个线程通用同步工具
    private CountDownLatch latch;
    private AsynchronousServerSocketChannel asynchronousServerSocketChannel;

    public AsyncTimeServerHandler() throws IOException {
        asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
        asynchronousServerSocketChannel.bind(new InetSocketAddress(HostInfo.PORT));
        System.out.println("服务器开启");
    }


    @Override
    public void run() {
        //latch的作用完成一组正在执行的操作之前,允许当前线程一直阻塞
        latch = new CountDownLatch(1);
        doAccept();
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void doAccept(){
        //接收客户端的链接
        //由于是一步操作,可以传递一个CompletionHandler实例接收accept操作成功的通知消息
        asynchronousServerSocketChannel.accept
                (this,new AcceptCompletionHandler());
    }

    public AsynchronousServerSocketChannel getAsynchronousServerSocketChannel() {
        return asynchronousServerSocketChannel;
    }

    public CountDownLatch getLatch() {
        return latch;
    }
}
